<template>
  <div id="contentRight">
    <section id="sec1">
      <p class="guide">
        <router-link to="/contractList">合约列表&nbsp;&nbsp;>&nbsp;</router-link>
        <span>转让</span>
      </p>
      <table>
        <thead>
        <tr>
          <td>名称</td>
          <td>金额(CNY)</td>
          <td>到手总算力</td>
          <td>合约期限</td>
          <td>合约状态</td>
          <td>开挖时间</td>
          <td>下单时间</td>
          <td>锁定时间</td>
        </tr>
        </thead>
        <tbody>
        <tr>
          <th>
            <span>{{machine.productName}}</span>
          </th>
          <th>
            <span>{{machine.state2 == 2 ? machine.continueTotalDeposit : machine.totalDeposit}}{{machine.payUnitName}}</span>
          </th>
          <th>
             <span class="pointer" @mouseenter="showItem1(machine , $event)" @mouseout="showWin1 = false">
               {{machine.handsPower}}T
             </span>
          </th>
          <th><span>{{machine.regularDateNum}}天</span></th>
          <th><span>{{machine.workText}}</span></th>
          <th><span>{{machine.startTime}}</span></th>
          <th><span>{{machine.operateTime}}</span></th>
          <th><span>{{machine.endTime}}</span></th>
        </tr>
        </tbody>
      </table>
    </section>
    <section id="sec2">
      <div class="d1">
        <span class="title">转让份额：</span>
        <div class="right">
          <input type="number" placeholder="请输入转让份额" v-model="transferNum"  onkeyup="value=value.replace(/^(0+)|[^\d]+/g,'')">
          <span class="reminder">拥有算力份额:{{machine.num}}份</span>
        </div>
      </div>
      <div class="d2">
        <span class="title">转让单价：</span>
        <div class="right">
          <input type="number" v-model="transferPrice" placeholder="请输入转让单价">
          <span class="reminder colorYellow">转让价格高于公允价格，将收取1%手续费</span>
        </div>
      </div>
      <div class="d3">
        <span class="title">公允价格：</span>
        <div class="right">{{acceptPrice}}{{priceUnit}} / T</div>
      </div>
      <div class="d4">
        <span class="title">手续费:</span>
        <div class="right">
          <label for="cnyPay" v-if="paymentCurrencyCode === 'CNY' || paymentCurrencyCode === 'BCNY'">
            <input type="radio" name="payMethod" id="cnyPay" value="CNY" v-model="payMethod">
            <span>CNY支付</span>
          </label>
          <label for="usdtPay" v-if="paymentCurrencyCode === 'USDT'" >
            <input type="radio" name="payMethod" id="usdtPay" value="USDT" v-model="payMethod">
            <span>USDT支付</span>
          </label>
          <label for="bhpPay">
            <input type="radio" name="payMethod" id="bhpPay" value="BHP" v-model="payMethod">
            <span>BHP支付</span>
          </label>
        </div>
      </div>
      <div class="d5">
        <span class="title">交易密码</span>
        <div class="right">
          <input type="password" placeholder="请输入交易密码" v-model="pws">
        </div>
      </div>
      <div class="d6">
        <span class="title">总额(不含手续费):</span>
        <span class="right">{{totalPayNum}}{{priceUnit}}</span>
      </div>
      <div class="d7">
        <label for="agree">
          <input type="checkbox" name="agree" v-model="agree" id="agree">
          <span>我同意</span>
          <a href="javascript: void  0;" @click.stop="showAgreement">《{{agreement.name}}》</a>
        </label>
      </div>
      <div class="d8">
        <button @click="sub">立即转让</button>
      </div>
    </section>
    <!--展示算力包的power信息-->
    <div class="abWin" v-if="showWin1" :style="win1Style">
      <span class="top">
        <span>总算力</span>
        <span>{{win1Data.totalPower}}T</span>
      </span>
      <span class="line">
        <span>
          <span class="left">基础算力</span>
          <span class="right">{{win1Data.basePower}}T</span>
        </span>
        <span>
          <span class="left">浮动算力</span>
          <span class="right">{{win1Data.floatPower}}T</span>
        </span>
        <span>
          <span class="left">达标算力</span>
          <span class="right">{{win1Data.standardPower}}T</span>
        </span>
        <span>
          <span class="left">期货算力</span>
          <span class="right">{{win1Data.futuresPower}}T</span>
        </span>
        <span>
          <span class="left">定期算力</span>
          <span class="right">{{win1Data.regularPower}}T</span>
        </span>
        <span>
          <span class="left">邀请算力</span>
          <span class="right">{{win1Data.invitePower}}T</span>
        </span>
      </span>
    </div>
    <confirm-dialog ref="transfer" @confirm="confirmTransfer"/>
    <confirm-dialog ref="transfer2"/>
    <transfer-confirm ref="transfer3" @confirm="confirmTransferAjax"/>
    <agreement-dialog ref="ag"/>
  </div>
</template>
<script>
  import { orderDetail  , leftMoney , transferMachine , transferMachineVerfily , transferAgreement , transferOrder } from '../http/api';
  export default {
    name: 'transferOrder',
    inject: ['reload'],
    data() {
      return {
        machine : {},
        win1Data : {
          totalPower : 0,
          basePower : 0 ,
          floatPower : 0,
          standardPower : 0,
          futuresPower : 0,
          regularPower : 0,
          invitePower : 0,
        },//弹窗1数据
        showWin1 : false,//显示弹窗1
        win1Style : {left : 0 ,right : 0}, //弹窗1位置
        payMethod : 'CNY',
        transferNum : '',//转让数量
        acceptPrice :  '--' ,//公允价格
        priceUnit : '',//公用价格单位
        agree: false,//同意协议
        totalPayNum : 0,//总支付金额
        transferPrice : '',//转让单价
        pws : '',//交易密码
        agreement : {},//协议
        orderId : null,
        paymentCurrencyCode : null,//订单的支付方式
      }
    },
    watch:{
      'pws'(){
        this.pws =  this.pws.replace(/[^\d]+/g,'').slice(0,6);
      },
      transferNum(num){
        let machine = this.machine;
        let max = machine.num;
        if(num > max){
          this.transferNum = max;
        }
        this.mathTotalPay();
      },
      transferPrice(price){
        this.mathTotalPay();
      }
    },
    mounted() {
      let query =  this.$route.query;
      let orderId = query.orderId;
      if(!orderId){
        require('../common/js/toast').toast('页面地址未传入订单id');
        this.$router.go(-1);
        return;
      }
      this.orderId = orderId;
      this.loadPage();
    },
    components:{
      AgreementDialog : resolve => { require(['../components/AgreementDialog'], resolve) },/*协议弹窗*/
      ConfirmDialog : resolve => { require(['../components/ConfirmDialog'], resolve) },/*确认弹窗*/
      TransferConfirm : resolve => { require(['../components/transferConfirm'], resolve) },/*转让信息确认*/
    },
    methods:{
      loadPage(){
        let thiz = this;
        let https = [
          transferAgreement({noToast : true , noLoading : true }).then(res => {
            if(res.code == 200){
              let data = res.data;
              this.agreement = data;
            }
          }),
          orderDetail({orderId : this.orderId , noLoading : true}).then(res => {
            if(res.code == 200){
              let data = res.data;
              let standardPrice = thiz.accMoreMul(data.basePower, 425, data.num);//标准价格
              if (data.paymentCurrencyCode != "USDT") {
                standardPrice = thiz.accMoreMul(data.basePower, 3000, data.num);
              }
              data.payUnitName = data.paymentCurrencyCode == "BCNY" ? "OTC余额" : data.paymentCurrencyCode;//金额单位名称
              let paymentCurrencyCode = data.paymentCurrencyCode;
              this.paymentCurrencyCode = paymentCurrencyCode;
              if(paymentCurrencyCode === 'USDT'){
                this.payMethod = 'USDT';
              }
              let win1Data = this.getPbHandPower(data);
              data.handsPower = win1Data.totalPower;
              thiz.machine = data;
              thiz.priceUnit = data.rawPaymentCurrencyCode == "BCNY" ? "CNY" : data.rawPaymentCurrencyCode;
              let acceptPrice = this.accDiv(data.rawTotalDeposit, thiz.accMul(data.rawNum, data.basePower));
              if (data.paymentCurrencyCode == "USDT") {
                this.acceptPrice = this.numSlice(acceptPrice, 4);
                //getDevNew = this.numSlice(getDevNew, 4);
              } else {
                this.acceptPrice = this.numSlice(acceptPrice, 2);
                // getDevNew = this.numSlice(getDevNew, 2);
              }
              // thiz.win1Data = win1Data;
            }
            return res;
          }),
          leftMoney({noLoading : true}).then(res => {
            let data = res.data;
            thiz.myMoney = thiz.numSlice(data.lists.CNY, 2);
            thiz.myUsdt = thiz.numSlice(data.lists.USDT, 4);
          })
        ];
        this.PromiseAll(https , res => {
          thiz.checkedDaysIndex = 0;
        });
      },
      getPbHandPower(item){
        //获取普通的合约包到手算力
        let win1Data = {
          //totalPower : this.accMoreMul(item.basePower , item.num),
          basePower : this.accMoreMul(item.basePower , item.num), //基础算力
          floatPower : this.accMoreMul(item.floatPower, item.num),//浮动
          standardPower : this.accMoreMul(item.pePower || 0, item.num),//达标
          futuresPower : this.accMoreMul(item.futuresPower, item.num),//期货
          regularPower : this.accMoreMul(item.regularPower, item.num),//定期
          invitePower : 0,//邀请
        };
        let result = 0 , thiz = this;
        this.for(win1Data , ( item , key ) => {
          result = thiz.accAddMore( result , item);
        });
        win1Data.totalPower = result;
        return win1Data;
      },
      showItem1(item , e ){
        let x = e.clientX;
        let y = e.clientY;
        this.win1Style = {left : x+20+'px' , top : y-30 +'px'};
        this.win1Data = this.getPbHandPower(item);
        this.showWin1 = true;
      },
      mathTotalPay(){
        let num = Number(this.transferNum);
        let machine = this.machine;
        let price = Number(this.transferPrice);
        if(price && num){
          let totalMoney = String(this.accMul(this.accMul(num, price), machine.basePower));
          let reTwo = /([0-9]+\.[0-9]{0,2})[0-9]*/;
          let refour = /([0-9]+\.[0-9]{0,4})[0-9]*/;
          let totalPayNum = 0;
          if (machine.paymentCurrencyCode == "USDT") {
            totalPayNum = totalMoney.replace(refour, "$1");
          } else {
            totalPayNum = totalMoney.replace(reTwo, "$1");
          }
          this.totalPayNum = totalPayNum;
        }

      },
      sub(){
        //点击提交
        let info = null;
        if( !this.transferNum ){
          info = '请输入转让份额';
        }else if(!this.transferPrice){
          info = '请输入转让价格';
        }else if(!this.pws){
          info = '请输入交易密码';
        }else if(!this.agree){
          info = '请阅读并同意协议';
        }
        if( info ){
          require('../common/js/toast').toast(info);
          return
        }
        info = `您确定以价格${this.transferPrice}${this.priceUnit}转让${this.transferNum}份合约吗？`;
        this.$refs.transfer.changeToast(info);
        this.$refs.transfer.dialogShow();
      },
      confirmTransfer(){
        //确认提交
        let param = {
          order_id: this.orderId,
          amount : this.transferPrice ,
          poundage_type: this.payMethod,
          pay_currency:  this.machine.rawPaymentCurrencyCode,
          num:  this.transferNum,
          noToast : true ,
          noLoading : true
        };
        this.loading();
        let https = [
          transferMachineVerfily({order_id: this.orderId, num: this.transferNum , noToast : true , noLoading : true}).then( res => {
            if(res.code == 200){
              // let msg = "<p style='padding: 0 15px;line-height: 175%'>"+res.message+"</p>";
              // this.$refs.transfer2.changeToast(msg);
              // this.$refs.transfer2.dialogShow();
              return res;
            }
          }),
          transferMachine(param).then(res => {
            if(res.code == 200){
              return res;
              // require('../common/js/toast').toast('转让成功');
              // this.$router.push({path : '/contractList'});
            }
          }),
        ];
        Promise.all(https).then(response =>{
          this.closeLoading();
          let res = response[0];
          let res2 = response[1];
          let res2Data = res2.data;
          let msg = res.message;
          let dialogData = {
            power : this.transferNum,
            price : this.transferPrice,
            totalTransferMoney : this.totalPayNum,
            poundage : res2Data.is_have_poundage == 1 ? res2Data.amount : 0,
            poundageCny : res2Data.cny,
            reminderInfo : msg,
            rate : res2Data.rate,
            is_have_poundage : res2Data.is_have_poundage,
            machinePriceUnit :  this.priceUnit ,
            canGet : this.totalPayNum + this.priceUnit ,
            poundageType : res2Data.type,
          };
          this.$refs.transfer3.getData(dialogData);
          this.$refs.transfer3.show();
        });
      },
      confirmTransferAjax(){
        let param = {
          order_id: this.orderId,
          num:  this.transferNum,
          trade_password : this.pws,
          poundage_type: this.payMethod,
          constract_id : this.machine.constractId,
          amount : this.transferPrice,
        };
        let thiz = this;
        transferOrder(param).then(res => {
          if(res.code == 200){
            require('../common/js/toast').toast('转让成功');
            thiz.timeout(function () {
              thiz.$router.push({path : '/contractList'});
            },1000)
          }
        });
      },
      showAgreement(){
        let agreement = this.agreement;
        this.$refs.ag.agreement(agreement.content , agreement.name);
      }
    }
  }
</script>
<style lang="less" scoped>
  @import "../common/style/common";
  @import "../common/style/public.css";
  #sec1{
    >table{
      width: 100%;text-align: left;margin-top: 15px;
      th{
        font-weight: 500;font-size: 14px;color: #262626;
        >span{
          display: inline-block;height: 100%;
        }
      }
      >thead{
        color: #999999;font-size: 14px;
        tr>td{
          padding: 25px 0;
          &:last-child{
            text-align: right;
          }
        }
      }
      >tbody{
        th{
          padding: 24px 6px;padding-top: 0px;color: #262626;font-size: 14px;vertical-align: text-top;
        }
        tr>th:first-child{
          max-width: 220px;
        }
        >tr>th:last-child{
          text-align: right;
        }
        .pointer{
          .colorYellow;text-decoration: underline;
          &:hover{
            cursor: pointer;
          }
        }
        .setting{
          >span{
            display: inline-block;width: 100%;text-align: right;margin-top: 15px;
            &:first-child{
              margin-top: 0px;
            }
          }
        }
      }
    }
  }
  #sec2{
    margin-top: 10px;
    >div{
      overflow: hidden;padding-top: 20px;
      &:first-child{
        padding-top: 0;
      }
      >.title{
        color: #898989;font-size: 14px;line-height: 38px;height: 38px;width: 85px;display: inline-block;text-align: left;float: left;
      }
      >.right{
        float: left;overflow: hidden;
        >input{
          .input();height: 38px;float: left;width: 322px;
        }
        >.reminder{
          float: left;font-size: 14px;padding-left: 23px;color: #999999;line-height: 38px;height: 38px;
        }
      }
    }
    >.d2{
      >.right>.colorYellow{
        .colorYellow;
      }
    }
    >.d3{
      >.right{
        height: 38px;line-height: 38px;
      }
    }
    >.d4{
      >.right{
        height: 38px;padding-top: 11px;
        >label{
          .radioLabel;margin-left: 50px;color: #595959;
          >span:before{
            border-color: #BFBFBF;
          }
          &:first-child{
            margin-left: 20px;
          }
        }
      }
    }
    >.d6{
      >.title{
        width: auto;
      }
      >.right{
        height: 38px; line-height: 38px;padding-left: 13px;
      }
    }
    >.d7{
      padding-left: 85px;text-align: left;
      >label{
        .checkLabel;
        >input{
          width: 25px;
        }
        >a{
          .colorYellow;
        }
      }
    }
    >.d8{
     padding: 45px 0; padding-left: 85px;
      button{
        .submit;width: 160px;height: 38px;font-size: 14px;line-height: 38px;
      }
    }
  }
</style>
